#include "historybook.h"
#include "ui_historybook.h"

#include <QDir>
#include <QTextCodec>
#include <QTreeWidget>

HistoryBook::HistoryBook(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::HistoryBook)
{
    ui->setupUi(this);
    initWindow();
    addEvents();
}

HistoryBook::~HistoryBook()
{
    delete ui;
}

void HistoryBook::initWindow(){
    this->setLayout(ui->mainLayout);
    // 禁止所有单元格编辑
    ui->tableWidget->setEditTriggers(QAbstractItemView::NoEditTriggers);
    // 隐藏垂直表头
    ui->tableWidget->verticalHeader()->setVisible(false);
    // 禁止调整列宽
    QHeaderView *header = ui->tableWidget->horizontalHeader();
    header->setSectionResizeMode(QHeaderView::Fixed);  // 设置列宽为固定

    ui->startDateEdit->setCalendarPopup(true);
    ui->endDateEdit->setCalendarPopup(true);
    ui->startDateEdit->setDate(QDate::currentDate());
    ui->endDateEdit->setDate(QDate::currentDate());

    QString separator = QDir::separator();
    QString currentDir= getCurrentCppDirectory();
    qDebug()<<"当前目录："<<currentDir;
    borroweredBookFilePath="borrowbooks.txt";
    returnedBookFilePath="HistoryBooks.txt";

    initBooks();

    currentShowData=historyBooks;
    setDataToTable();

}

void HistoryBook::initBooks(){
    historyBooks.clear();
QTextCodec* codec = QTextCodec::codecForName("UTF-8");
    QFile file1(borroweredBookFilePath);
    if (file1.open(QIODevice::ReadOnly | QIODevice::Text)) {
        QTextStream in(&file1);
        in.setCodec(codec);
        while (!in.atEnd()) {
            QString line = in.readLine();
            qDebug() << "未归还数据：" << line;

            QStringList dataList = line.split("/");
            if (dataList.size() < 9) {
                qWarning() << "数据格式错误：" << line;
                continue;
            }

            QString name = dataList[0];
            QString publisher = dataList[1];
            QString author = dataList[2];
            QString ISBN = dataList[3];
            QString categroy = dataList[4];
            QString collectionLocation = dataList[5];
            int currentCollection = dataList[6].toInt();
            int allCollection = dataList[7].toInt();
            QDate loanTime = QDate::fromString(dataList[8], "yyyy-MM-dd");

            BorrowedBook* book = new BorrowedBook(name, publisher, author, ISBN, categroy, collectionLocation, currentCollection, allCollection, loanTime, nullptr);
            historyBooks.append(book);
        }
        file1.close();
    } else {
        qWarning() << "无法打开文件，错误信息：" << file1.errorString();
    }

    QFile file2(returnedBookFilePath);
    if (file2.open(QIODevice::ReadOnly | QIODevice::Text)) {
        QTextStream in2(&file2);
        in2.setCodec(codec);
        while (!in2.atEnd()) {
            QString line = in2.readLine();
            qDebug() << "已归还数据：" << line;

            QStringList dataList = line.split("/");
            if (dataList.size() < 10) {
                qWarning() << "数据格式错误：" << line;
                continue;
            }

            QString name = dataList[0];
            QString publisher = dataList[1];
            QString author = dataList[2];
            QString ISBN = dataList[3];
            QString categroy = dataList[4];
            QString collectionLocation = dataList[5];
            int currentCollection = dataList[6].toInt();
            int allCollection = dataList[7].toInt();
            QDate loanTime = QDate::fromString(dataList[8], "yyyy-MM-dd");
            QDate returnTime = QDate::fromString(dataList[9], "yyyy-MM-dd");

            BorrowedBook* book = new ReturnedBook(name, publisher, author, ISBN, categroy, collectionLocation, currentCollection, allCollection, loanTime, nullptr, returnTime);
            historyBooks.append(book);
        }
        file2.close();
    } else {
        qWarning() << "无法打开文件，错误信息：" << file2.errorString();
    }

    std::sort(historyBooks.begin(),historyBooks.end(),[](BorrowedBook *a, BorrowedBook *b) {
        return a->getLoanTime() > b->getLoanTime(); // 根据借阅时间排序
    });
}

void HistoryBook::addEvents(){
    QObject::connect(ui->searchButton,&QPushButton::clicked,this,&HistoryBook::searchEvent);
    connect(ui->startDateEdit, &QDateEdit::dateChanged, this, &HistoryBook::checkDateRange);
    connect(ui->endDateEdit, &QDateEdit::dateChanged, this, &HistoryBook::checkDateRange);
}
// 定义一个函数来获取当前cpp文件所在目录
QString HistoryBook::getCurrentCppDirectory()
{
    QString filePath = __FILE__;
    QDir dir(filePath);
    dir.cdUp();
    return dir.path();
}

void HistoryBook::setDataToTable(){
    ui->tableWidget->clearContents();
    ui->tableWidget->setRowCount(0);
    // 填充表格
    for (int row = 0; row < currentShowData.size(); row++) {
        ui->tableWidget->insertRow(ui->tableWidget->rowCount());
        ui->tableWidget->setRowHeight(row,50);

        // 设置各列数据，封装成独立的函数，使代码结构更清晰
        setTableItem(row, 0, currentShowData[row]->getISBN(), Qt::AlignCenter, 12);
        setTableItem(row, 1, currentShowData[row]->getName(), Qt::AlignCenter, 12);
        setTableItem(row, 2, currentShowData[row]->getAuthor(), Qt::AlignCenter, 12);
        setTableItem(row, 3, currentShowData[row]->getCategory(), Qt::AlignCenter, 12);
        setTableItem(row, 5, currentShowData[row]->getLoanTime().toString("yyyy-MM-dd"), Qt::AlignCenter, 12);
        ReturnedBook*book=dynamic_cast<ReturnedBook*>(currentShowData[row]);
        if(book){
            QTableWidgetItem* item = new QTableWidgetItem("已归还");
            QFont font = item->font();
            font.setPointSize(12);
            item->setFont(font);
            // 设置文字颜色为绿色
            item->setForeground(Qt::green);
            item->setTextAlignment(Qt::AlignCenter);
            ui->tableWidget->setItem(row, 4, item);
            setTableItem(row, 6, book->getReturnTime().toString("yyyy-MM-dd"), Qt::AlignCenter, 12);
        }else{
            QTableWidgetItem* item = new QTableWidgetItem("未归还");
            QFont font = item->font();
            font.setPointSize(12);
            item->setFont(font);
            // 设置文字颜色为红色
            item->setForeground(Qt::red);
            item->setTextAlignment(Qt::AlignCenter);
            ui->tableWidget->setItem(row, 4, item);

            QTableWidgetItem* item2 = new QTableWidgetItem("等待归还中...");
            item2->setFont(font);
            // 设置文字颜色为红色
            item2->setForeground(Qt::red);
            item2->setTextAlignment(Qt::AlignCenter);
            ui->tableWidget->setItem(row, 6, item2);
            //setTableItem(row, 6, "等待归还中...", Qt::AlignCenter, 12);
        }
    }

    ui->countLabel->setText("共"+QString::number(currentShowData.size())+"/"+QString::number(historyBooks.size())+"条数据");
    ui->countLabel->setAlignment(Qt::AlignRight);
}

// 辅助函数：统一设置表格项的格式和内容
void HistoryBook::setTableItem(int row, int column, const QString& text, Qt::Alignment alignment, int fontSize) {
    QTableWidgetItem* item = new QTableWidgetItem(text);
    QFont font = item->font();
    font.setPointSize(fontSize);
    item->setFont(font);
    item->setTextAlignment(alignment);
    ui->tableWidget->setItem(row, column, item);
}

//根据搜索条件展示数据
void HistoryBook::setDataToTable(QDate startDate,QDate endDate){
    currentShowData.clear();
    for(BorrowedBook*book:historyBooks){
        if(book->getLoanTime()>=startDate&&book->getLoanTime()<=endDate){
            currentShowData.append(book);
        }
    }
    setDataToTable();
}

void HistoryBook::searchEvent(){
    qDebug()<<"搜索按钮按下";
    QDate startDate=ui->startDateEdit->date();
    QDate endDate=ui->endDateEdit->date();
    setDataToTable(startDate,endDate);
}

void HistoryBook::keyPressEvent(QKeyEvent *event){
    qDebug()<<"按钮监听："<<event->key()<<" "<<event->text();
    if(event->key()==Qt::Key_Return||event->key()==Qt::Key_Enter){
        QWidget*focusWidget=this->focusWidget();
        if(qobject_cast<QDateEdit*>(focusWidget)){
            searchEvent();
        }
    }
}

void HistoryBook::checkDateRange(const QDate& date)
{
    // 检查是哪个QDateEdit发出的信号
    if (sender() == ui->startDateEdit)
    {
        if (date > ui->endDateEdit->date())
        {
            ui->startDateEdit->setDate(ui->endDateEdit->date());
        }
    }
    else if (sender() == ui->endDateEdit)
    {
        if (date < ui->startDateEdit->date())
        {
            ui->endDateEdit->setDate(ui->startDateEdit->date());
        }
    }
}
